Based on simple example of app in which we can create, read, update and delete simple text documents
Component installation
The official site of nodejs (https://nodejs.org/) has detailed installation instructions
For centos:
1 | $ curl —silent —location https://rpm.nodesource.com/setup_9.x | sudo bash - |
For Ubuntu:1
2
3$ curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ sudo apt-get install -y build-essential
Organize a folder for the project and execute a command for project initialization in it:1
$ npm init
Answer the following questions
- Project name
- Project version
- Description
- Entry point
- Testing team
- Githhab’s repository
- Project keywords
- Author
- License
Confirm and you’ll see file package.json, describing the project.
Now install the remaining components: Express and MongoDB (the latest version of the plugin does not work correctly with the database, so it’s better to install an earlier one):1
$ npm install --save express mongodb@2.2.16
Also, for the convenience of handling url-encoded requests, install the body-parser:1
$ npm install --save body-parser
And for the convenience of development, it is better to install Nodemon, which will restart the server every time when any files change:1
$ npm install --save-dev nodemon
To attach Nodemon, you need to add the following to package.json:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20{
"name": "notable",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error^ no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongodb": "^2.2.16"
},
"devDependencies": {
"nodemon": "^1.14.2"
}
}
To be able to test app install Postman(https://www.getpostman.com/), which will simulate requests
Starting the server
Create file server.js in root directory, in which we write dependencies, specify the port and start listening:1
2
3
4
5
6
7
8const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});
Run the server:1
npm run dev
In the terminal you can now see the message “We are live on port 8080”
Structure of project
For more convenient structuring of the project it is necessary to create an ‘app’ folder, in it we create the ‘routes’ folder, and in it - files ‘index.js’ and ‘note_routes.js’
So, the structure looks like this: in app/ routes - our route handlers, in the node_modules folder - the modules of our project, and server.js directly describes our server.
Connecting the DB
Add the ‘config’ directory to the project root, create a ‘db.js’. file in it.
In the file db.js write the following:1
2
3module.exports = {
url : 'mongodb://localhost:27017/<yourDataBase>'
};
In the file ‘server.js’ we add:1
2
3
4
5
6
7
8
9
10
11
12
13
14const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require(‘./config/db’);
const app = express();
const port = 8080;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
require(‘./app/routes’)(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
});
Creating a text document
In app/routes/note_routes.js we write:1
module.exports = function(app, db) { };
In app/routes/index.js:1
2
3
4
5
6
7
8
9
10
11
12
13const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
Reading a text document
By analogy with app.post, we write another method:1
2
3
4
5
6
7
8
9
10
11app.get('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
Deleting of text document
By analogy with app.post, we write another method:1
2
3
4
5
6
7
8
9
10
11app.delete('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
db.collection('notes').remove(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send('Note ' + id + ' deleted!');
}
});
});
Updating of text document
By analogy with app.post, we write another method:1
2
3
4
5
6
7
8
9
10
11
12app.put ('/notes/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').update(details, note, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(note);
}
});
});
Testing with Postman
Postman allows specify the type of request (get, post, put, update), it’s address and port and add various parameters to the request body, for example, an empty POST request on the 8080 port.
Upon execution of the request, we see the server response.
Example of a POST request with a filled body:
Let the server print the request to the server console, then we’ll see:
Links
Node installing
https://nodejs.org/en/download/package-manager/#enterprise-linux-and-fedora
Postman installing
https://www.getpostman.com/
Similar articles
- https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2#.eybmlr1g9
- https://habrahabr.ru/company/ruvds/blog/321104/
- https://loftblog.ru/material/4-podklyuchenie-bazy-dannyx-k-express/
- http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/